package ui.panels.strategies.manual;

import gameEngine.agents.choosingStrategy.representation.ManuallAdaptiveRepresentation;
import gameEngine.agents.choosingStrategy.representation.StrategyRepresentation;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.table.DefaultTableModel;

import ui.panels.commands.SetStrategyRepresentationCommand;
import Data.ConfigurationParameters;
import auxiliary.AuxiliaryClass;

public class ManualListener implements ActionListener{
	private ManualPanel manualPanel = null;
	
	public ManualListener(ManualPanel panel)
	{
		this.manualPanel = panel;
	}
	
	public void actionPerformed(ActionEvent event) {
		
		//case is the addStrategy button
		if(event.getSource() == manualPanel.getAddStrategy())
		{	
			//add new strategy to the table
			manualPanel.addRow(ConfigurationParameters.Strategy.EGREEDY);
		}
		
		//case it is Ok button, should save
		else if(event.getSource() == manualPanel.getOk())
		{
			DefaultTableModel 	model = null;

			
			//save the strategies
			ManuallAdaptiveRepresentation mAdaptiveRepresentation = new 
						ManuallAdaptiveRepresentation(ConfigurationParameters.Strategy.MANUAL_ADAPTIVE);
			
			
			model = manualPanel.getModel();
			//loop over the strategies in the table
			for(int i = 0; i < manualPanel.getNumRows(); ++i)
			{
				//get the strategy from the combo box

				String type = (String) model.getValueAt(i, 0);
				StrategyRepresentation sRepresentation = manualPanel.createStrategyRepresentation(type);
				
				//case the type not exist 
				if(type == null)
					continue;
									
				//number of turns
				String turnsStr = (String) model.getValueAt(i, 1);
				 if(AuxiliaryClass.isNumber(turnsStr))
				 {
					 int turns = Integer.parseInt(turnsStr);
					 mAdaptiveRepresentation.addStrategy(sRepresentation, turns);
				 }
			}
			
			//set the strategy in player properties panel
			SetStrategyRepresentationCommand setStrategyRepresentationCommand =
								new SetStrategyRepresentationCommand();
			setStrategyRepresentationCommand.setStrategyRepresentation(mAdaptiveRepresentation);
			setStrategyRepresentationCommand.execute();
			
			//enable and close this panel's frame
			manualPanel.setEnablePrimePanelAndClose();
		}
		
		//case it is Cancel button, close the window
		else if(event.getSource() == manualPanel.getCancel())
		{
			manualPanel.setEnablePrimePanelAndClose();
		}
	}

}
